<script setup>
import { ref, reactive, onBeforeMount, h, onMounted } from 'vue'
import request from "@/utils/request";
import { ElMessage, ElNotification } from 'element-plus';


const tableData = ref([])
const total = ref(0)
const rules = reactive({
  id: [{ required: true, trigger: 'blur', message: "请输入学号" }],
  className: [{ required: true, trigger: 'blur', message: "请输入班级" }],
  name: [{ required: true, trigger: 'blur', message: "请输入姓名" }]
});
const ruleFormRef = ref();
const dialogFormVisible = ref(false);
const formLabelWidth = "80px";
let state = reactive({ form: {} })
let form2 = ref({});
const dialogFormVisible2 = ref(false);
//api
const resetTable = () => {
  total.value = 0;
  tableData.value = [];
}

//生命周期函数
onMounted(async () => {
  //初始化表格数据
  const response = await request.get("/table/page/" + 1 + "/" + 8);
  tableData.value = response.records;
  total.value = response.total;
});


//按钮
//1.搜索        通过姓名关键字进行模糊查询
const keyword = ref('');
const queryByKeyWord = async () => {
  var response = await request.get("/table/page?" + "pageNum=" + 1 + "&pageSize=8" + "&input=" + keyword.value);
  console.log(keyword.value);
  tableData.value = response.records;
  total.value = response.total;
  // console.log(response.records);
  if (response.total === 0) {
    ElMessage('未查询到数据');
  }
}

//点击页码实现数据切换
const handleCurrentChange = async (num) => {
  var all_data = await request.get("/table/all");
  if (total.value != all_data.length) {
    //搜索之后进行页码切换。
    var response = await request.get("/table/page?" + "pageNum=" + num + "&pageSize=8" + "&input=" + keyword.value);
    tableData.value = response.records;
  } else {
    //未进行搜索，页码切换。
    var response2 = await request.get("/table/page/" + num + "/" + 8)
    tableData.value = response2.records;
  }
};

//2.新增
const handleAdd = () => {
  dialogFormVisible.value = true;
  state.form = reactive({})
}
const comfirmAndAddStudent = () => {
  // console.log(form);          //  proxy(object)       vue3中的响应式对象
  //取出proxy(object)对象中的真实数据，   这里采用序列化方法获取
  // console.log(JSON.parse(JSON.stringify(form)));
  var form_params = JSON.parse(JSON.stringify(state.form));

  //校验表单是否合法
  ruleFormRef.value.validate(valid => {
    if (valid) {
      request.post("/table/", form_params).then(res => {
        // console.log(res);
        if (res) {
          ElMessage.success({
            message: '保存成功',
            type: 'success',
          })
          dialogFormVisible.value = false;
          queryByKeyWord();
        } else {
          ElMessage({
            showClose: true,
            message: '保存失败',
            type: 'error',
          })
        }
      })
    }
  });

}

//3.批量删除
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  var list = JSON.parse(JSON.stringify(val))
  // console.log(list);
  multipleSelection.value = list
};

const batchDeletion = async () => {
  let ids = JSON.parse(JSON.stringify(multipleSelection.value)).map(x => x.id);
  // console.log(ids);
  if (ids.length == 0) {
    ElMessage({
      message: '未选中数据',
      type: 'warning',
    })
    return;
  };
  request.post("/table/delete/batch", ids).then(res => {
    if (res) {
      ElMessage({
        showClose: true,
        message: '批量操作成功',
        type: 'success',
      });
    } else {
      ElMessage.error('批量删除失败！')
    }
  })
  var response = await request.get("/table/page?" + "pageNum=" + 1 + "&pageSize=8" + "&input=" + keyword.value);
  console.log(keyword.value);
  tableData.value = response.records;
  total.value = response.total;
}

//4.导入
const importBtn = () => {
  ElNotification({
    title: '提示',
    message: h('i', { style: 'color: teal' }, '数据导入 只接受*.xlsx文件格式的数据！'),
    type: 'info'
  })
}

//5.导出
const exportBtn = async () => {
  window.open("http://localhost:10029/table/export")

  // let wb = XLSX.utils.table_to_book(document.querySelector('#my-table'));//关联dom节点
  // var wbout = XLSX.write(wb, {
  //   bookType: 'xlsx',
  //   bookSST: true,
  //   type: 'array'
  // });
  // try {
  //   FileSaver.saveAs(new Blob([wbout], {
  //     type: 'application/octet-stream'
  //   }), '学生信息.xlsx')//自定义文件名
  // } catch (e) {
  //   if (typeof console !== 'undefined') console.log(e, wbout);
  // }
  // return wbout;
}

//6.精准操作：编辑
const handleEdit = (raw) => {
  // console.log(JSON.parse(JSON.stringify(raw)));
  //将选中的学生数据赋值给 编辑表单
  form2 = JSON.parse(JSON.stringify(raw));
  // console.log(form2);
  dialogFormVisible2.value = true
}

const editAndSave = () => {
  var form_params = JSON.parse(JSON.stringify(form2));

  request.put("/table/", form_params).then(res => {
    console.log(res);
    if (res) {
      ElMessage.success({
        message: '保存成功',
        type: 'success',
      })
      dialogFormVisible.value = false;
    } else {
      ElMessage({
        showClose: true,
        message: '保存失败',
        type: 'error',
      })
    }
  });
  dialogFormVisible2.value = false
}

//7.精准操作；删除
const deleteThisInfo = async (id) => {
  // console.log(id);
  var res = await request.delete("/table/" + id);
  if (res) {
    ElMessage({
      showClose: true,
      message: '操作成功',
      type: 'success',
    })
  }
  var response = await request.get("/table/page?" + "pageNum=" + 1 + "&pageSize=8" + "&input=" + keyword.value);
  console.log(keyword.value);
  tableData.value = response.records;
  total.value = response.total;
}
</script>

<template>
  <el-card style="margin: 0px 2%;">
    <div>
      <div style="margin: 15px 0;">
        <el-input style="width: 400px;" placeholder="请输入关键词（姓名、班级或者学号）" v-model="keyword"
          @keyup.enter.native="queryByKeyWord()">
          <template #suffix>
            <el-icon @click="keyword = ''">
              <CloseBold />
            </el-icon>
          </template>
        </el-input>
        <el-button style="margin-left: 5px;padding: 0 20px;" type="primary" @click="queryByKeyWord()">
          <el-icon style="vertical-align: middle; ">
            <Search />
          </el-icon>
          搜索
        </el-button>
        <el-button style="margin-left: 5px; padding: 0 20px;" type="warning" @click="resetTable()">
          <el-icon style="vertical-align: middle;">
            <Refresh />
          </el-icon>
          重置
        </el-button>
      </div>

      <div style="margin:15px 0;">
        <el-button type="success" @click="handleAdd()" size="large">
          新增
          <el-icon>
            <Plus />
          </el-icon>
        </el-button>

        <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
          icon-color="#626AEF" title="你确定进行批量删除吗？" @confirm="batchDeletion()">
          <template #reference>
            <el-button type="danger" size="large">
              批量删除
              <el-icon>
                <Close />
              </el-icon>
            </el-button>
          </template>
        </el-popconfirm>

        <el-upload v-model:file-list="fileList" action="/table/export" style="display: inline-block;"
          :show-file-list="false" accept="'xlsx'">
          <el-button type="primary" @click="importBtn()" size="large" style="margin: 0 10px;"> 导入
            <el-icon>
              <Bottom />
            </el-icon>
          </el-button>
        </el-upload>

        <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
          icon-color="#626AEF" title="即将导出全部学生信息，确定继续吗？" @confirm="exportBtn()">
          <template #reference>
            <el-button type="primary" size="large">导出
              <el-icon>
                <Top />
              </el-icon>
            </el-button>
          </template>
        </el-popconfirm>
      </div>

      <el-table :data="tableData" stripe border @selection-change="handleSelectionChange"
        :header-cell-style="{ 'background': '#EFEFEF' }" id="my-table">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="学号" sortable></el-table-column>
        <el-table-column prop="className" label="班级"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="success" @click="handleEdit(scope.row)">编辑
              <el-icon>
                <EditPen />
              </el-icon>
            </el-button>

            <el-popconfirm title="确定删除该条数据吗，操作不可逆。" :icon="InfoFilled" width="220" icon-color="#626AEF"
              @confirm="deleteThisInfo(scope.row.id)">
              <template #reference>
                <el-button type="danger">删除
                  <el-icon>
                    <CloseBold />
                  </el-icon>
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="没有找到相关数据哦。" />
        </template>

      </el-table>

      <div style="margin: 15px 0;">
        <el-pagination background layout="total, prev, pager, next, jumper" :total="total"
          @current-change="handleCurrentChange" />
      </div>

      <el-dialog v-model="dialogFormVisible" title="新增学生信息" width="30%">
        <el-form :model="state.form" :rules="rules" ref="ruleFormRef" status-icon>
          <el-form-item label="学号" prop="id" :label-width="formLabelWidth">
            <el-input v-model="state.form.id" autocomplete="off" />
          </el-form-item>
          <el-form-item label="班级" prop="className" :label-width="formLabelWidth">
            <el-input v-model="state.form.className"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
            <el-input v-model="state.form.name"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="comfirmAndAddStudent()">
              确认添加
            </el-button>
          </span>
        </template>
      </el-dialog>


      <el-dialog v-model="dialogFormVisible2" title="编辑学生信息" width="30%">
        <el-form :model="form2" :rules="rules" ref="ruleFormRef2" status-icon>
          <el-form-item label="学号" prop="id" :label-width="formLabelWidth">
            <el-input v-model="form2.id" autocomplete="off" />
          </el-form-item>
          <el-form-item label="班级" prop="className" :label-width="formLabelWidth">
            <el-input v-model="form2.className"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
            <el-input v-model="form2.name"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible2 = false">取消</el-button>
            <el-button type="primary" @click="editAndSave()">
              确定修改
            </el-button>
          </span>
        </template>
      </el-dialog>

    </div>
  </el-card>
</template>

<style lang='scss' scoped></style>